﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using Common.Utilities;
using OnlineVideos.Data;
using System.Threading;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using PicasaMobileInterface;
using InsertIntoDataBase;
using OnlineVideos.Views;
using OnlineVideos.Entities;
using System.Threading.Tasks;

namespace OnlineMovies.Views
{
    public partial class Story : PhoneApplicationPage
    {
        public static string oldimage = string.Empty;
        public string ImageUrl = string.Empty;
        public string PageName = string.Empty;
        public static string imagetype = string.Empty;
        public bool TaskNavigation = false;
        public AutoResetEvent auto = new AutoResetEvent(false);
        public static bool navigated = false;
        public Story()
        {
            InitializeComponent();
            Loaded += Story_Loaded;
        }

        void Story_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationContext.QueryString.TryGetValue("PageName", out PageName))
            {

            }
            if (Constants.editstory == true)
            {
                if(ResourceHelper.AppName==Apps.Story_Time.ToString())
                tblkVideosTitle.Text = "Edit Story Paragraph";
                else
                    tblkVideosTitle.Text = "Edit Vedic Paragraph";
            }
            else
            {
                if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                tblkVideosTitle.Text = "Add Story Paragraph";
                else
                    tblkVideosTitle.Text = "Add Vedic Paragraph";
            }
            int showid = AppSettings.ShowUniqueID;
            List<Stories> str = new List<Stories>();
            List<Stories> str1 = new List<Stories>();
            if (Constants.editstory == true)
            {

                int paraid = Constants.ParaId;
                str = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.paraId < paraid).OrderByDescending(i => i.paraId).ToListAsync()).Result.Take(2).ToList();
                str1 = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.paraId > paraid).OrderBy(i => i.paraId).ToListAsync()).Result.Take(2).ToList();
            }
            else
            {


                str =Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid).OrderByDescending(i => i.ID).ToListAsync()).Result.Take(2).ToList();

            }
            if ((Constants.editstory == true) ? (str.Where(i => i.Image != "").FirstOrDefault() != null || str1.Where(i => i.Image != "").FirstOrDefault() != null) : str.Where(i => i.Image != "").FirstOrDefault() != null)
            {
                storyonlineimg.MouseLeftButtonDown -= storyonlineimg_MouseLeftButtonDown_1;
                storylocalimg.MouseLeftButtonDown -= storylocalimg_MouseLeftButtonDown_1;

            }
            if (Constants.editstory == true)
            {


                int paraid = Constants.ParaId;

                tblkdes.Text = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.paraId == paraid).FirstOrDefaultAsync()).Result.Description;

                string imagename = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.paraId == paraid).FirstOrDefaultAsync()).Result.Image;
                if (Task.Run(async()=>await Storage.FileExists(Constants.storyImagePath + AppSettings.ShowUniqueID + "/" + imagename)).Result)
                {
                    Constants.UIThread = true;
                    storylocalimg.Source = ResourceHelper.getStoryImageFromStorageFolder(imagename);
                    Constants.UIThread = false;
                }
            }
            if (Constants.UserImage1 != null)
            {

                Constants.UIThread = true;
                if (imagetype == "LocalImage")
                {
                    if (string.IsNullOrEmpty(Constants.newimage))
                        storylocalimg.Source = new BitmapImage(new Uri("/Images/fromlocal.png", UriKind.RelativeOrAbsolute));
                    else
                        storylocalimg.Source = ResourceHelper.getStoryImageFromStorageFolder(AppSettings.ImageTitle + ".jpg");
                    storyonlineimg.Source = new BitmapImage(new Uri("/Images/fromonline.png", UriKind.RelativeOrAbsolute));
                }
                if (imagetype == "OnlineImage")
                {
                    if (string.IsNullOrEmpty(Constants.newimage))
                        storyonlineimg.Source = new BitmapImage(new Uri("/Images/fromonline.png", UriKind.RelativeOrAbsolute));
                    else
                        storyonlineimg.Source = ResourceHelper.getStoryImageFromStorageFolder(AppSettings.ImageTitle + ".jpg");
                    storylocalimg.Source = new BitmapImage(new Uri("/Images/fromlocal.png", UriKind.RelativeOrAbsolute));
                }
                Constants.UIThread = false;
             

            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (TaskNavigation == false)
            {
                if (Constants.Description.Length > 0)
                {
                    txtlimit.Visibility = Visibility.Collapsed;
                    tblkdes.Text = Constants.Description.ToString();
                    txtlength.Text = Convert.ToString(tblkdes.Text.Length) + "/" + Convert.ToString(4000);

                }
                if (Constants.UserImage1 != null && Constants.navigation == false)
                {

                    if (navigated == false)
                    {
                        navigated = true;
                        NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + AppSettings.ImageTitle + "&type=Story", UriKind.Relative));
                    }
                    else
                    {
                        navigated = false;
                        //Constants.UIThread = true;
                        //if (imagetype == "LocalImage")
                        //{
                        //    if (Constants.newimage == string.Empty)
                        //        storylocalimg.Source = new BitmapImage(new Uri("/Images/fromlocal.png", UriKind.RelativeOrAbsolute));
                        //    else
                        //        storylocalimg.Source = ResourceHelper.getStoryImageFromStorageFolder(AppSettings.ImageTitle + ".jpg");
                        //    storyonlineimg.Source = new BitmapImage(new Uri("/Images/fromonline.png", UriKind.RelativeOrAbsolute));
                        //}
                        //if (imagetype == "OnlineImage")
                        //{
                        //    if (Constants.newimage == string.Empty)
                        //        storyonlineimg.Source = new BitmapImage(new Uri("/Images/fromonline.png", UriKind.RelativeOrAbsolute));
                        //    else
                        //    storyonlineimg.Source = ResourceHelper.getStoryImageFromStorageFolder(AppSettings.ImageTitle + ".jpg");
                        //    storylocalimg.Source = new BitmapImage(new Uri("/Images/fromlocal.png", UriKind.RelativeOrAbsolute));
                        //}
                        //Constants.UIThread = false;
                        //Constants.UserImage = null;
                    }

                }
                else
                    Constants.navigation =false;
            }
            else
            {
                TaskNavigation = false;
            }
        }
        private void storylocalimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.navigation = true;
            imagetype = "LocalImage";
            int paraid = Constants.ParaId;
        
            oldimage = (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.paraId == paraid).FirstOrDefaultAsync()).Result != null) ? Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.paraId == paraid).FirstOrDefaultAsync()).Result.Image : string.Empty;
            if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID).OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result== null)
            {
                AppSettings.ImageTitle = "1";
            }
            else
            {
                string image = string.Empty;
                if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID ==  AppSettings.ShowUniqueID &&  i.Image != "").OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result != null)
                {
                    image = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID &&  i.Image != "").OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result.Image;
                }
                else
                {
                    image = string.Empty;
                }

                if (!string.IsNullOrEmpty(image))
                    AppSettings.ImageTitle = Convert.ToString(Convert.ToInt32(image.Substring(0, image.IndexOf(".jpg"))) + 1);
                else
                    AppSettings.ImageTitle = "1";
            }
            PhotoChooserTask task = new PhotoChooserTask();
            task.Completed += task_Completed;
            task.Show();
            TaskNavigation = true;
        }
        void task_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                Constants.UserImage1 = new BitmapImage();
                Constants.UserImage1.SetSource(e.ChosenPhoto);
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri("/Views/PhotoChooser.Xaml?ImageName=" + AppSettings.ImageTitle + "&type=Story", UriKind.Relative));

                });

                // userimg.Source = bitmapimage;
            }


        }

        private void storyonlineimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

            imagetype = "OnlineImage";
            int paraid = Constants.ParaId;
         
            oldimage = (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.paraId == paraid).FirstOrDefaultAsync()).Result != null) ? Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.paraId == paraid).FirstOrDefaultAsync()).Result.Image : string.Empty;
            if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID).OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result == null)
            {
                AppSettings.ImageTitle = "1";
            }
            else
            {
                string image = string.Empty;
                if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.Image != "").OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result != null)
                {
                    image = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.Image != "").OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result.Image;
                }
                else
                {
                    image = string.Empty;
                }

                if (!string.IsNullOrEmpty(image))
                    AppSettings.ImageTitle = Convert.ToString(Convert.ToInt32(image.Substring(0, image.IndexOf(".jpg"))) + 1);
                else
                    AppSettings.ImageTitle = "1";
            }
            var bingKey = Constants.bingsearch(ResourceHelper.AppName);
            var authentication = string.Format("{0}:{1}", string.Empty, bingKey);
            var encodedKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(authentication));
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Image%27&Query=%27Yevadu%27&Adult=%27Off%27&ImageFilters=%27Size%3AMedium%27");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.datamarket.azure.com/Bing/Search/v1/Image?Query='" + AppSettings.Title + " Movie" + "'&ImageFilters=%27Style%3aPhoto%2bSize%3aMedium%2bAspect%3aTall%27&$top=50&$format=Atom");
            request.Method = "GET";
            request.Headers["Authorization"] = "Basic " + encodedKey;
            request.BeginGetResponse(new AsyncCallback(RequestBlogCompleted), request);

        }
        private void RequestBlogCompleted(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(result);
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                string responseStr = responseReader.ReadToEnd();
                Stream strm = new MemoryStream(Encoding.UTF8.GetBytes(responseStr));
                XElement MyXMLConfig = XElement.Load(strm);
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                XNamespace Img = "http://schemas.microsoft.com/ado/2007/08/dataservices";
                XNamespace met = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

                Constants.OnlineImageUrls = new ObservableCollection<string>(MyXMLConfig.Descendants(atomNS + "entry").Descendants(met + "properties").Elements().Where(i => i.Name == Img + "MediaUrl").Select(i => i.Value).ToList());

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                });
            }
            catch (Exception ex)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    PageHelper.NavigateToOnlineImagesPage(AppResources.OnlineImagesPageName);
                });
            }
        }

        private void tblkdes_TextChanged_1(object sender, TextChangedEventArgs e)
        {
            txtlimit.Visibility = Visibility.Collapsed;
            txtlength.Text = Convert.ToString(tblkdes.Text.Length) + "/" + Convert.ToString(4000);
        }

        private void onlinedescimg_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.navigation = true;
            NavigationService.Navigate(new Uri("/Views/UserBrowserPage.xaml?querytext=" + AppSettings.Title + "&searchquery=" + string.Empty, UriKind.RelativeOrAbsolute));
        }

        private void edit_MouseLeftButtonDown_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Constants.Description.Clear();
            Constants.Description.Append(tblkdes.Text);
            Constants.navigation = true;
            NavigationService.Navigate(new Uri("/Views/Description.Xaml", UriKind.Relative));
        }

        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

        }

        private void btnsave_Click_1(object sender, EventArgs e)
        {
            if (tblkdes.Text.Length > 4000)
            {

                txtlimit.Visibility = Visibility.Visible;

            }
            else
            {

                txtlimit.Visibility = Visibility.Collapsed;
                storylocalimg.Source = null;
                storyonlineimg.Source = null;

                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork += bg_DoWork;
                bg.RunWorkerCompleted += bg_RunWorkerCompleted;
                //bg.RunWorkerAsync(tblkpersonname.Text);
                bg.RunWorkerAsync();

            }
        }
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
         
            int showid = AppSettings.ShowUniqueID;
            int paraid = Constants.ParaId;
            if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid).OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result == null)
            {
                AppSettings.ImageTitle = "1";
            }
            else
            {
                string image = string.Empty;
                if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid &&  i.Image != "").OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result != null)
                {
                    image =Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.Image != "").OrderByDescending(i => i.Image).FirstOrDefaultAsync()).Result.Image;
                }
                else
                {
                    image = string.Empty;
                }
                if (!string.IsNullOrEmpty(image))
                    AppSettings.ImageTitle = Convert.ToString(Convert.ToInt32(image.Substring(0, image.IndexOf(".jpg"))) + 1);
                else
                    AppSettings.ImageTitle = "1";

            }
            string ImageName = AppSettings.ImageTitle + ".jpg";
           IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
           if (isoStore.FileExists(Constants.storyImagePath +"/"+ AppSettings.ShowUniqueID + "/" + ImageName))
           {

               ImageUrl = string.Empty;
               BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogType == "shows").FirstOrDefaultAsync()).Result;
               if (NetworkHelper.IsNetworkAvailableForDownloads())
               {
                   PicasaInterface pi = new PicasaInterface(bt.BlogUserName, bt.BlogPassword);
                   uploadImage(ImageName);
               }
           }
           else
           {
               ImageUrl =string.Empty;
           }
        }
        public void uploadImage(string imagename)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://picasaweb.google.com/data/feed/api/user/" + CONST.USER);
            request.Method = "POST";
            request.ContentType = "image/png";
            request.Headers["Authorization"] = CONST.PIC_AUTH + CONST.AUTH_Token;
            object[] array = new object[2];
            array[0] = imagename;
            array[1] = request;
            request.BeginGetRequestStream(new AsyncCallback(GetPicasaStreamCallback), array);
            auto.WaitOne();
        }

        private void GetPicasaStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                object[] array = new object[2];
                array = (object[])asynchronousResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)array[1];

                string ImageName = array[0].ToString();

                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream fileStream = isoStore.OpenFile(Constants.storyImagePath + AppSettings.ShowUniqueID + "/" + ImageName, FileMode.Open);
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                byte[] buffer = new byte[fileStream.Length / 4];
                int bytesRead = -1;
                fileStream.Position = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    postStream.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
                postStream.Close();
                isoStore.Dispose();
                request.BeginGetResponse(new AsyncCallback(RequestPicasaCompleted), request);
            }
            catch (Exception ex)
            {
                auto.Set();
            }
        }

        private void RequestPicasaCompleted(IAsyncResult result)
        {
            try
            {
                var request = (HttpWebRequest)result.AsyncState;
                var response = (HttpWebResponse)request.EndGetResponse(result);
                StreamReader responseReader = new StreamReader(response.GetResponseStream());
                XElement MyXMLConfig = XElement.Load(responseReader);
                XNamespace atomNS = "http://www.w3.org/2005/Atom";
                ImageUrl = MyXMLConfig.Descendants(atomNS + "content").Attributes().Where(i => i.Name == "src").FirstOrDefault().Value;
                auto.Set();
            }
            catch (Exception ex)
            {
                auto.Set();
            }

        }
        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
          
            int showid = AppSettings.ShowUniqueID;
            int paraid = Constants.ParaId;
            if (Constants.ParaId != default(int))
            {
                Stories s =Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid && i.paraId == paraid).FirstOrDefaultAsync()).Result;


                s.Description = tblkdes.Text;
                if (!string.IsNullOrEmpty(Constants.newimage))
                {
                    s.Image = AppSettings.ImageTitle + ".jpg";
                    s.FlickrStoryImageUrl = ImageUrl;
                    Constants.newimage = string.Empty;

                    if (!string.IsNullOrEmpty(oldimage))
                    {
                        if (s.Image != oldimage)
                        {
                            string FolderName = "Images\\storyImages";
                            if (Task.Run(async()=>await Storage.FileExists("Images/storyImages/" + showid + "/"+oldimage)).Result)
                            {
                                Storage.DeleteFile("Images/storyImages/" + showid + "/" + oldimage);
                            }
                            oldimage = string.Empty;
                        }

                    }
                }
                Constants.connection.UpdateAsync(s);
                Constants.editstory = false;
            }
            else
            {
              
                InsertData<Stories> insert = new InsertData<Stories>();
                insert.ParameterList = new Stories();
                insert.ParameterList.ShowID = showid;
                insert.ParameterList.Description = tblkdes.Text;
                insert.ParameterList.LanguageID = 1;
                insert.ParameterList.Title = AppSettings.Title;
                if (Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result == null)
                    insert.ParameterList.paraId = 1;
                else
                    insert.ParameterList.paraId = Task.Run(async()=>await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid).OrderByDescending(i => i.paraId).FirstOrDefaultAsync()).Result.paraId + 1;
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (!isoStore.FileExists(Constants.storyImagePath + "/" + AppSettings.ShowUniqueID + "/" + AppSettings.ImageTitle + ".jpg"))

                    insert.ParameterList.Image = "";
                else
                {
                    if (!string.IsNullOrEmpty(Constants.newimage))
                    {
                    insert.ParameterList.Image = AppSettings.ImageTitle + ".jpg";
                    Constants.newimage = string.Empty;
                    }
                }
               insert.ParameterList.FlickrStoryImageUrl = ImageUrl;
                insert.Insert();
            }
            AppSettings.ImageTitle = string.Empty;
            Constants.UserImage1 = null;
            Constants.Description.Clear();
            if (Constants.ParaId != default(int))
            {

                Constants.ParaId = default(int);
            }
         if(string.IsNullOrEmpty(PageName))
           NavigationService.GoBack();
            else
         {
             Random ran=new Random();
             NavigationService.Navigate(new Uri("/Views/"+PageName+"?PageID="+ran.Next(1,99), UriKind.Relative));
         }
           
            
            //NavigationService.Navigate(new Uri("/Views/StoryDetails.xaml", UriKind.Relative));
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
           
            if (Constants.ParaId != default(int))
            {

                Constants.ParaId = default(int);
            }
            Constants.Description.Clear();
            Constants.UserImage1 = null;
            Constants.editstory = false;
        }
    }
}